package com.gaoboy.springbootgoods.controller;

import com.gaoboy.springbootgoods.entity.User;
import com.gaoboy.springbootgoods.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("user/queryAll")
    @ResponseBody
    public List<User> queryAll() {
        return userService.queryAll();
    }

    @RequestMapping("toLogin")
    public String toLogin() {
        return "login";
    }


    @RequestMapping("/doLogin")
    public String doLogin(String username, String password, HttpServletRequest request) {
        User user = userService.doLogin(username, password);
        HttpSession session = request.getSession();
        session.setAttribute("loginUser", username);
        session.setAttribute("userId", user.getId());
        return "forward:/goods/queryByDynamicFields";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(String username, String password) {
        User user = userService.doLogin(username, password);
        if (user == null) {
            return "false";
        }
        if (new Date().after(user.getValidateEndTime())) {
            return "outOfDate";
        }
        return "true";
    }

    @RequestMapping("/register")
    @ResponseBody
    public String register(String username, String password) {
        return userService.register(username, password);
    }
}
